package com.CooKieTest;

import com.whenJay.HelloWorldServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;


@WebServlet("/c1")
public class CookieDemo01 extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解决中文乱码问题
        resp.setContentType("text/html;charset=utf-8");
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");

        PrintWriter out = resp.getWriter();
        //服务器从客户端获取
        Cookie[] cookies = req.getCookies();


        //判断Cookie是否存在
        if(cookies != null){
            //如果存在:
            out.write("你上次访问的时间是:");

            for(int i=0 ; i < cookies.length ; i++){
                Cookie cookie = cookies[i];
                //获取cookie的名字
                if(cookie.getName().equals("lastLoginTime")){
                    //System.out.println(cookie.getValue());
                    long lastLoginTime = Long.parseLong(cookie.getValue());
                    Date date = new Date(lastLoginTime);
                    out.write(URLDecoder.decode(date.toLocaleString()));
                }
            }
        }else{
                out.write("这是你第一访问本站");

        }
        Cookie cookie = new Cookie("lastLoginTime", System.currentTimeMillis()+"");
        resp.addCookie(cookie);
    }


}
